<template>
  <div class="w-full h-full overflow-auto bg-white-soft">
    <div class="mt-6">
      <div class="ui FHContainer">
        <div class="FHMain">
          <div class="FHContent flex flex-row">
            <div class="content">
              <div v-if="data.dataInitialized">
                <!-- 问题内容-->
                <div class="border-box bg-white">
                  <h1 class="text-3xl font-bold">{{ data.questionDetail.title }}</h1>
                  <p class="mt-3">{{ data.questionDetail.summary }}</p>
                  <UserPostInfo :user-name="data.questionDetail.createBy" :post-time="data.questionDetail.createTime"
                                class="mt-3"/>
                  <el-divider/>
                  <div class="min-h-[300px]">
                    <Editor
                        style=""
                        v-model="data.questionDetail.content"
                        :defaultConfig="{readOnly: true}"
                        mode="default"
                        @onCreated="handleContentEditorCreated"/>
                  </div>
                  <div>
                    <div class="question-tags">
                      <a class="border rounded-md p-1 select-none font-bold">大数据</a>
                      <a class="border rounded-md p-1 select-none font-bold">flink</a>
                    </div>
                    <div class="mt-6 flex flex-row">
                      <ClickToggleCounter active-icon="/svg/start-selected.svg"
                                          inactive-icon="/svg/start.svg"
                                          :flag="data.questionDetail.hasStart" :count="data.questionDetail.starCount"
                                          @OnInactive="()=>{data.questionDetail.hasStart=false;data.questionDetail.starCount--;cancelThumbsUpAnswer(data.questionDetail.id)}"
                                          @onActive="()=>{data.questionDetail.hasStart=true;data.questionDetail.starCount++;thumbsUpAnswer(data.questionDetail.id);}"/>

                      <span class="ml-6"><img alt="Icon" width="18" height="18"
                                              src="/svg/share.svg"
                                              @click=""
                                              class="hover:scale-110"
                                              id="share-btn"/></span>
                    </div>
                  </div>
                </div>

                <!-- 回复区-->
                <div class="border-box bg-white">
                  <p class="font-bold text-xl">发表回答</p>
                  <Transition>
                    <div class="mt-3" v-if="!answerQuestion">
                      <span>请在回答中保持友善和尊重，让我们一起营造一个积极、健康的交流环境！</span>
                      <el-button class="ml-2" type="primary" @click="answerQuestion = true">撰写回答</el-button>
                    </div>
                    <div class="mt-3 answer-div" v-else>
                      <Toolbar
                          style="border-bottom: 1px solid var(--el-border-color)"
                          :editor="answerEditorRef"
                          :defaultConfig="{}"
                          mode="default"
                      />
                      <Editor
                          class="border-b"
                          style="height: 500px; overflow-y: hidden;"
                          v-model="data.answerContent"
                          :defaultConfig="{placeholder: '请输入内容...', autoFocus: false, maxLength: 2000}"
                          mode="default"
                          @onCreated="handleAnswerEditorCreated"
                          @onMaxLength="onEditorMaxLength"/>
                      <div class="mt-3">
                        <el-button type="primary" @click="onPublishQuestionAnswer"
                                   :disabled="checkAnswerContentEmpty()">提交
                        </el-button>
                        <el-button class="ml-2" type="info" @click="answerQuestion = false">取消</el-button>
                      </div>
                    </div>
                  </Transition>
                </div>

                <!-- 回答区-->
                <div class="border-box bg-white" v-show="data.questionAnswers.total > 0">
                  <p class="font-bold text-xl">{{ formatNumberSimple(data.questionAnswers.total) }}个回答</p>
                  <div v-for="answer in data.questionAnswers.records">
                    <el-divider/>
                    <UserPostInfo :user-name="answer.createBy" :post-time="answer.createTime"
                                  class="mt-3"/>
                    <Editor
                        style=""
                        v-model="answer.content"
                        :defaultConfig="{readOnly: true}"
                        mode="default"/>
                    <div class="mt-3">
                      <ClickToggleCounter active-icon="/svg/thumbs-up-selected.svg"
                                          inactive-icon="/svg/thumbs-up.svg"
                                          :flag="answer.hasThumbsUp" :count="answer.voteCount"
                                          @OnInactive="()=>{answer.hasThumbsUp=false;answer.voteCount--;cancelThumbsUpAnswer(answer.id)}"
                                          @onActive="()=>{answer.hasThumbsUp=true;answer.voteCount++;thumbsUpAnswer(answer.id);}"/>
                    </div>
                  </div>
                  <el-pagination
                      class="mt-3"
                      v-model:current-page="data.questionAnswers.current"
                      v-model:page-size="data.questionAnswers.size"
                      :page-sizes="[10, 20, 50, 100]"
                      :total="data.questionAnswers.total"
                      background
                      layout="sizes, prev, pager, next"
                      @change="handleAnswerPageChange"
                      hide-on-single-page
                  />
                </div>
              </div>
              <div v-else>
                <el-skeleton/>
                <el-divider/>
              </div>
            </div>
            <div class="aside">
              <div class="aside-container px-5 py-6">
                <div class="ad mt-4">
                  <el-carousel height="150px" motion-blur>
                    <el-carousel-item>
                      <el-image src="/images/ad/gandi.png"></el-image>
                    </el-carousel-item>
                    <el-carousel-item>
                      <el-image src="/images/ad/tencent.png"></el-image>
                    </el-carousel-item>
                  </el-carousel>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {onBeforeUnmount, onMounted, reactive, ref, shallowRef} from 'vue'
import {QuestionAnswerPageResp, QuestionAnswerPublishReq, QuestionDetailResp} from '@/api/qa/types'
import {getQuestionDetail, pageQuestionAnswer, publishQuestionAnswer} from '@/api/qa'
import {useRoute} from "vue-router";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import UserPostInfo from "@/components/common/UserPostInfo.vue";
import {formatNumberSimple} from '@/utils/math'
import {ElMessage, ElMessageBox} from "element-plus";
import ClickToggleCounter from "@/components/feedback/ClickToggleCounter.vue";
import {IDomEditor} from "@wangeditor/editor";

const route = useRoute()
const data = reactive({
  dataInitialized: false,
  questionId: null as number,
  questionDetail: {} as QuestionDetailResp,
  questionAnswers: {current: 1, size: 10, pages: 10, total: 100, records: [] as Array<QuestionAnswerPageResp>},
  answerContent: ''
})
const contentEditorRef = shallowRef()
const answerEditorRef = shallowRef()
const answerQuestion = ref(false)
const loadQuestionDetail = (id: number) => {
  getQuestionDetail(id).then(result => {
    data.questionDetail = result
    data.dataInitialized = true
  })
}

const loadQuestionAnswer = (questionId: number, page?: number) => {
  const req = {
    questionId: questionId,
    current: page ? page : data.questionAnswers.current,
    size: data.questionAnswers.size
  }
  pageQuestionAnswer(req).then(result => {
    data.questionAnswers = result
  })
}
const handleAnswerPageChange = (currentPage: number, pageSize: number) => {
  loadQuestionAnswer(data.questionId, currentPage)
}

const thumbsUpAnswer = (questionId: number) => {
}

const cancelThumbsUpAnswer = (questionId: number) => {
}

const startQuestion = (questionId: number) => {
}

const cancelStartQuestion = (questionId: number) => {
}

const handleAnswerEditorCreated = (editor) => {
  answerEditorRef.value = editor
}
const handleContentEditorCreated = (editor) => {
  contentEditorRef.value = editor
}
const onEditorMaxLength = (editor: IDomEditor) => {
  ElMessageBox.alert('超出最大长度限制', '提示', {
    confirmButtonText: '知道了'
  })
}
const checkAnswerContentEmpty = () => {
  if (answerEditorRef.value == undefined) {
    return true
  }
  return answerEditorRef.value.isEmpty()
}
const onPublishQuestionAnswer = () => {
  const req: QuestionAnswerPublishReq = {
    questionId: data.questionId,
    content: data.answerContent
  }
  publishQuestionAnswer(req).then(() => {
    ElMessage({
      message: '回答成功',
      type: 'success',
    })
    data.answerContent = ''
    loadQuestionAnswer(data.questionId, 1)
    answerQuestion.value = false
  })
}

//初始加载数据
onMounted(() => {
  data.questionId = Number(route.query.id)
  if (data.questionId == null || isNaN(data.questionId)) {
    ElMessage({
      type: 'error',
      message: '缺少必要参数'
    })
    return
  }
  loadQuestionDetail(data.questionId)
  loadQuestionAnswer(data.questionId)
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    setTimeout(() => {
      if (answerEditorRef.value != null) answerEditorRef.value.destroy()
      if (contentEditorRef.value != null) contentEditorRef.value.destroy()
    }, 200)
})
</script>
<style>
.question-tags a {
  background-color: rgb(241, 242, 243);
}

.question-tags a:not(:first-child) {
  margin-left: 0.50rem;
}

.v-enter-active,
.v-leave-active {
  transition: opacity 0.3s ease;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
</style>